const fs = require('fs')
const path = require('path')

module.exports = {
  get: async(ctx, next) => {
    let url = ctx.url;
    var html = await route(url)
    ctx.body = html
  },
  fileUpload: async(ctx, next) => {
    console.log(ctx.request.body.files.resource)
    ctx.type = ctx.request.body.files.resource.type
    ctx.body = Buffer.from(fs.readFileSync(ctx.request.body.files.resource.path)) //返回文件名  

  },
  download: async(ctx, next) => {
    console.log(ctx.params)
    var imgName = ctx.params.name
    ctx.attachment(imgName)
    ctx.body = Buffer.from(fs.readFileSync(path.resolve(__dirname, '../public/uploads/' + imgName)))
  }
}

function render(page) {
  return new Promise((resolve, reject) => {
    let viewUrl = `./views/${page}`
    fs.readFile(viewUrl, "utf-8", (err, data) => {
      if (err) {
        reject(err)
      } else {
        resolve(data)
      }
    })
  })
}

async function route(url) {
  let view = '404.html'
  switch (url) {
    case '/':
      view = 'index.html'
      break
    case '/index':
      view = 'index.html'
      break
    case '/user':
      view = 'user.html'
      break
    case '/404':
      view = '404.html'
      break
    default:
      break
  }
  let html = await render(view)
  return html
}